<?php

namespace app\controllers;

use Yii;
use yii\web\Controller;
use yii\helpers\Html;
use app\common\ArrayHelper;
use app\models\TResourceInfo;
use app\models\BCourseKnowledgePoint;
use app\models\TCourseEvaluate;
use Faker\Provider\Uuid;
use yii\helpers\Url;

class ResourceController extends Controller{
    public $enableCsrfValidation = false;
    public function init()
    {
        parent::init();
        header('Access-Control-Allow-Origin: *');
    }
    /*
     * 微信小程序获取媒体类型(用于获取课程资源的所有媒体类型)
     * gyq
     * 2019/12/12
     * */
    public function  actionGetMediaType(){
        $sql="select * from t_sys_dictionary where del_flag=0 and type='resourceType'";
        $mediaTypeInfo=\yii::$app->db->createCommand($sql)->queryAll();
        foreach ($mediaTypeInfo as $key=>$value){
            $dataInfo[]=['mediaCode'=>$value['value'],'mediaName'=>$value['name']];
        }
        $result = [
            "state" => true,
            "code" => 200,
            "message"=>"",
            "data"=>$dataInfo
        ];
        \yii::$app->end(json_encode($result));
    }
    /*
 * 微信小程序获取应用类型(用于获取课程资源的所有应用类型)
 * gyq
 * 2019/12/12
 * */
    public function  actionGetApplicationType(){
        $sql="select * from t_sys_dictionary where del_flag=0 and type='resourceAppliedType'";
        $resourceAppliedTypeInfo=\yii::$app->db->createCommand($sql)->queryAll();
        foreach ($resourceAppliedTypeInfo as $key=>$value){
            $dataInfo[]=['applicationCode'=>$value['value'],'applicationName'=>$value['name']];
        }
        $result = [
            "state" => true,
            "code" => 200,
            "message"=>"",
            "data"=>$dataInfo
        ];
        \yii::$app->end(json_encode($result));
    }
    /*
* 微信小程序获取课程资源的语言类型
* gyq
* 2019/12/27
* */
    public function  actionGetLanguageType(){
        $sql="select * from t_sys_dictionary where del_flag=0 and type='resourceLanguage'";
        $resourceLanguageInfo=\yii::$app->db->createCommand($sql)->queryAll();
        foreach ($resourceLanguageInfo as $key=>$value){
            $dataInfo[]=['resourceLanguageCode'=>$value['value'],'resourceLanguageName'=>$value['name']];
        }
        $result = [
            "state" => true,
            "code" => 200,
            "message"=>"",
            "data"=>$dataInfo
        ];
        \yii::$app->end(json_encode($result));
    }
    /*
* 微信小程序获取课程资源(根据条件获取对应的课程资源)
* gyq
* 2019/12/12
* */
    public function  actionQueryResourceList(){
            $pageIndex=isset($_REQUEST['pageIndex']) ? $_REQUEST['pageIndex'] : 1;
            $length=isset($_REQUEST['pageSize']) ? $_REQUEST['pageSize'] :10;
            $resourceLanguageType=isset($_REQUEST['resourceLanguageType']) ? $_REQUEST['resourceLanguageType'] : '';//媒体类型
            $mimeType=isset($_REQUEST['mediaType']) ? $_REQUEST['mediaType'] : '';//媒体类型
            $applicationType=isset($_REQUEST['applicationType']) ? $_REQUEST['applicationType'] : '';
            $searchTitle=isset($_REQUEST['keyword']) ? $_REQUEST['keyword'] : '';//关键字
            $projectId=isset($_REQUEST['projectId'])&&!empty($_REQUEST['projectId']) ? $_REQUEST['projectId'] : 6;//默认18 测试为6
            //定义查询数据总记录数sql
            $sumSql = "SELECT
	count(id)
FROM
	t_resource_info
WHERE
	del_flag = 0
AND project_id =:project_id";
            //查询资源总数
            $recordsTotal = \yii::$app->db->createCommand($sumSql)->bindValues([':project_id'=>$projectId])->queryScalar();
            //带条件过滤资源
            $where = "tri.project_id =:project_id ";
            if(!empty($mimeType)){
                $where .= " and trf.mime = '".$mimeType."'";
            }
            if(!empty($applicationType)){
                $where .= " and tri.mat_type = '".$applicationType."'";
            }
            if(!empty($resourceLanguageType)){
                $where .= " and tri.mat_lang = '".$resourceLanguageType."'";
            }
            if (strlen($searchTitle)>0) {
                $searchTitle=str_replace("'","''",$searchTitle);
                $where .=" and (tri.title LIKE '%".$searchTitle."%' OR tbu.pet_name LIKE '%".$searchTitle."%') ";
            }
            $where.="ORDER BY createTime DESC";
        //分页
            $start = ($pageIndex-1)*$length;//从多少开始
            $where.= " LIMIT ".intval($start).", ".intval($length);
            $totalResultSql = "SELECT
    tri.id,
	trf.size,
	tri.title AS name,
    tri.mat_intro AS introduction,
    tbu.pet_name AS author,
    tri.mat_diff AS difficulty,
    tri.source,
    tri.major_id AS profession,
    tri.school_id,
    tri.course_id,
    trf.mime AS mediaType,
	tri.mat_type AS applicationType,
	tri.create_time AS createTime,
	tri.create_by,
	trf.uri AS resourceLink,
	trf.type AS file_type
FROM
	t_resource_info tri
LEFT JOIN t_base_user_profile tbu ON tri.create_by = tbu.user_id
LEFT JOIN t_resource_file trf ON tri.file_id = trf.id
WHERE tri.del_flag=0  and ".$where;
        //直接查询所有记录
        $info = \yii::$app->db->createCommand($totalResultSql)->bindValues([':project_id'=>$projectId])->queryAll();
        $dataInfo=[];
        foreach ($info as $key => $value) {
            //查询知识点
                    $sql="SELECT
        p. name
    FROM
        b_course_knowledge_point p
    LEFT JOIN t_resource_knowledge_point_ref r ON r.point_id = p.id
    WHERE
        r.flag = 0
    AND p.del_flag = 0
    AND r.resource_id =:resource_id";
                    $pointInfo=\yii::$app->db->createCommand($sql)->bindValues([':resource_id'=>$value['id']])->queryAll();
                    $point="";
                    foreach ($pointInfo as $k=>$v){
                        $point.=$v['name'].",";
                    }
                    $point=trim($point,",");
                    //查询资源所属专业
                    $sql="select name from t_base_major_directory where del_flag=0 and uuid=:major_id";
                    $profession=\yii::$app->db->createCommand($sql)->bindValues([':major_id'=>$value['profession']])->queryScalar();
                    //查询所属单位
                    $school_name="";
                    if(!empty($value['school_id'])){
                        $sql="select school_name from t_base_school where del_flag=0 and id=:school_id";
                        $school_name=\yii::$app->db->createCommand($sql)->bindValues([':school_id'=>$value['school_id']])->queryScalar();
                    }else{
                        if(!empty($value['course_id'])){
                            //取课程所属学校
                            $sql="select school_name from b_course_info where id=:bcourseId";
                            $school_name=\yii::$app->db->createCommand($sql)->bindValues([':bcourseId'=>$value['course_id']])->queryScalar();
                        }
                    }
                    $url=\yii::$app->params['interFaceWeiXin'];
                    if(in_array($value['file_type'],['doc','docx'])){
                        $icon=$url."/weixin/resources/01.png";
                    }elseif(in_array($value['file_type'],['png','jpg','jpeg','JPG','PNG','JPEG','bmp','gif'])){
                        $icon=$url."/weixin/resources/02.png";
                    }elseif(in_array($value['file_type'],['xls','xlsx'])){
                        $icon=$url."/weixin/resources/03.png";
                    }elseif($value['file_type']=='pdf'){
                        $icon=$url."/weixin/resources/04.png";
                    }elseif($value['file_type']=='txt'){
                        $icon=$url."/weixin/resources/05.png";
                    }elseif(in_array($value['file_type'],['ppt','pptx'])){
                        $icon=$url."/weixin/resources/06.png";
                    }elseif($value['file_type']=='swf'){
                        $icon=$url."/weixin/resources/07.png";
                    }elseif(in_array($value['file_type'],['html','htm'])){
                        $icon=$url."/weixin/resources/08.png";
                    }elseif(in_array($value['file_type'],['ogg','ogv','mov','webm','mp3','wav','mid'])){
                        $icon=$url."/weixin/resources/09.png";
                    }else if(in_array($value['file_type'],['flv','mkv','avi','rm','rmvb','mp4','wmv'])){
                        $icon=$url."/weixin/resources/10.png";
                    }else{
                        $icon=$url."/weixin/resources/11.png";
                    }
                    $dataInfo[]=[
                        "resourceId"=>$value['id'],
                        "size"=> (int) $value['size'],
                        "name"=>$value['name'] ,
                        "introduction"=> $value['introduction'],
                        "author"=> $value['author'],
                        "difficulty"=>self::GetDictionaryNameByValue($value['difficulty']),
                        "source"=>self::GetDictionaryNameByValue($value['source']) ,
                        "profession"=>$profession ,
                        "unit"=>$school_name ,
                        "point"=>$point,
                        "mediaType"=>self::GetDictionaryNameByValue($value['mediaType']),
                        "applicationType"=>self::GetDictionaryNameByValue($value['applicationType']),
                        "createTime"=>!empty($value['createTime']) ? substr($value['createTime'],0,10): '' ,
                        "resourceLink"=> \yii::$app->params['fileUrlWeiXin'].$value['resourceLink'],
                        'icon'=>$icon
                    ];
                }
            $result=[
                "state"=>true,
                "code"=>200,
                "message"=>"",
                "data"=>[
                    "totalCount"=>(int)$recordsTotal,
                    "resourceList"=>$dataInfo
                ]
            ];
        \yii::$app->end(json_encode($result));
    }
    /**
     * 微信小程序开课目录资源列表接口
     * @param int  courseId:课程ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2019-12-25
     * @author: gyq
     */
    public function actionAppGetTcourseCatalog() {
        $error = array();
        $course_id = !empty($_REQUEST['courseId'])?$_REQUEST['courseId']:$error[]=array('课程ID不能为空');
        if(!empty($error)){
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }else{
            $url=\yii::$app->params['interFaceWeiXin'];
            $sql = "select * from t_course_item where course_id=:courseId and del_flag=0 and pid='0' order by sequence asc";
            $chapterList = Yii::$app->db->createCommand($sql)->bindValues([':courseId'=>$course_id])->queryAll();
            if(empty($chapterList)){
                $result = [
                    'msg' => '暂无内容',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '200'
                ];
                Yii::$app->end(json_encode($result));
            }
            $yiji = array();
            foreach ($chapterList as $chapter) {
                $sql="SELECT CASE
                            WHEN c.uri='' THEN
                                ''
                            WHEN c.mime='resourceType.weblink' THEN 
                                c.uri
                            WHEN c.mime='resourceType.document' THEN 
                                CONCAT(
                                    '".Yii::$app->params['docConvertUrl']. "&furl=" .Yii::$app->params['fileUrlWeiXin']."',
                                    c.uri
                                )
                            WHEN c.mime='resourceType.ppt' THEN 
                                CONCAT(
                                    '".Yii::$app->params['docConvertUrl']. "&furl=" .Yii::$app->params['fileUrlWeiXin']."',
                                    c.uri
                                )
                            ELSE
                                CONCAT(
                                    '".Yii::$app->params['fileUrlWeiXin']."',
                                    c.uri
                                )
                            END AS uri,a.id,a.item_id as pId,a.title as name,c.mime as type,2 as level,a.sequence,a.resourse_id as resourceId,a.create_by,c.type as file_type FROM t_course_item_resource_reference a LEFT JOIN t_resource_info b ON a.resourse_id=b.id LEFT JOIN t_resource_file c ON b.file_id=c.id WHERE a.item_id=:itemId AND a.course_id=:courseId AND a.del_flag=0 AND b.del_flag=0 AND c.del_flag=0 ORDER BY a.sequence asc";
                $resourceList = \Yii::$app->db->createCommand($sql)->bindValue(':itemId', $chapter['id'])->bindValue(':courseId', $course_id)->queryAll();
                if(!empty($resourceList)){
                    foreach ($resourceList as $key => $value) {
                        $resourceList[$key]['children'] = [];
                    }
                }
                //一级目录的目录
                $sql = "select id,pid as pId,title as name,'directory' as type,2 as level,sequence,create_by,'' as resourceId,'' as uri from t_course_item where pid='" . $chapter['id'] . "' and course_id='" . $course_id . "' and del_flag =0";
                $sectionList = Yii::$app->db->createCommand($sql)->queryAll();
                $erjiList = ArrayHelper::array_sort(array_merge($resourceList, $sectionList), 'sequence','asc');
                $sanji = array();
                foreach ($erjiList as $erji) {
                    if ($erji['type'] == 'directory') {
                        $sql="SELECT CASE
                                WHEN c.uri='' THEN
                                    ''
                                WHEN c.mime='resourceType.weblink' THEN 
                                    c.uri
                                WHEN c.mime='resourceType.document' THEN 
                                    CONCAT(
                                        '".Yii::$app->params['docConvertUrl']. "&furl=" .Yii::$app->params['fileUrlWeiXin']."',
                                        c.uri
                                    )
                                WHEN c.mime='resourceType.ppt' THEN 
                                    CONCAT(
                                        '".Yii::$app->params['docConvertUrl']. "&furl=" .Yii::$app->params['fileUrlWeiXin']."',
                                        c.uri
                                    )
                                ELSE
                                    CONCAT(
                                        '".Yii::$app->params['fileUrlWeiXin']."',
                                        c.uri
                                    )
                                END AS uri,a.id as id,a.item_id as pId,a.title as name,c.mime as type,3 as level,a.sequence,a.resourse_id as resourceId,a.create_by,c.type AS file_type,b.mime_type FROM t_course_item_resource_reference a LEFT JOIN t_resource_info b ON a.resourse_id=b.id LEFT JOIN t_resource_file c ON b.file_id=c.id WHERE a.item_id=:itemId AND a.course_id=:courseId AND a.del_flag=0 AND b.del_flag=0 AND c.del_flag=0 ORDER BY a.sequence asc";
                        $resourceList = \Yii::$app->db->createCommand($sql)->bindValue(':itemId', $erji['id'])->bindValue(':courseId', $course_id)->queryAll();
                        $resourceList_new = [];
                        foreach ($resourceList as $resource) {
                            if(in_array($resource['file_type'],['doc','docx'])){
                                $icon=$url."/weixin/course/01.png";
                            }elseif(in_array($resource['file_type'],['png','jpg','jpeg','JPG','PNG','JPEG','bmp','gif'])){
                                $icon=$url."/weixin/course/02.png";
                            }elseif(in_array($resource['file_type'],['xls','xlsx'])){
                                $icon=$url."/weixin/course/03.png";
                            }elseif($resource['file_type']=='pdf'){
                                $icon=$url."/weixin/course/04.png";
                            }elseif($resource['file_type']=='txt'){
                                $icon=$url."/weixin/course/05.png";
                            }elseif(in_array($resource['file_type'],['ppt','pptx'])){
                                $icon=$url."/weixin/course/06.png";
                            }elseif($resource['file_type']=='swf'){
                                $icon=$url."/weixin/course/07.png";
                            }elseif(in_array($resource['file_type'],['html','htm'])){
                                $icon=$url."/weixin/course/08.png";
                            }elseif(in_array($resource['file_type'],['ogg','ogv','mov','webm','mp3','wav','mid'])){
                                $icon=$url."/weixin/course/09.png";
                            }else if(in_array($resource['file_type'],['flv','mkv','avi','rm','rmvb','mp4','wmv'])){
                                $icon=$url."/weixin/course/10.png";
                            }else{
                                $icon=$url."/weixin/course/11.png";
                            }
                            $resourceList_new[] = array('id' => $resource['id'], 'pId' => $resource['pId'], 'name' => $resource['name'], 'type' => $resource['type'], 'level' => $resource['level'], 'sequence' => $resource['sequence'], 'resourceId' => empty($resource['resourceId']) ? '' : $resource['resourceId'], 'create_by' => $resource['create_by'],'uri' => $resource['uri'],'file_type'=>$resource['file_type'],'mime_type'=>$resource['mime_type'],'icon'=>$icon,'children'=>array());
                        }
                        $sql = "select id,pid as pId,title as name,'directory' as type,2 as level,sequence,create_by,'' as resourceId,'' as uri from t_course_item where pid='" . $erji['id'] . "' and course_id='" . $course_id . "' and del_flag =0";
                        $sectionLists = Yii::$app->db->createCommand($sql)->queryAll();
                        $sanjiList = ArrayHelper::array_sort(array_merge($resourceList_new, $sectionLists), 'sequence','asc');
                        $siji = array();
                        foreach ($sanjiList as $key => $value) {
                            if ($value['type'] == 'directory') {
                                $sql="SELECT CASE
                                        WHEN c.uri='' THEN
                                            ''
                                        WHEN c.mime='resourceType.weblink' THEN 
                                            c.uri
                                        WHEN c.mime='resourceType.document' THEN 
                                            CONCAT(
                                                '".Yii::$app->params['docConvertUrl']. "&furl=" .Yii::$app->params['fileUrlWeiXin']."',
                                                c.uri
                                            )
                                        WHEN c.mime='resourceType.ppt' THEN 
                                            CONCAT(
                                                '".Yii::$app->params['docConvertUrl']. "&furl=" .Yii::$app->params['fileUrlWeiXin']."',
                                                c.uri
                                            )
                                        ELSE
                                            CONCAT(
                                                '".Yii::$app->params['fileUrlWeiXin']."',
                                                c.uri
                                            )
                                        END AS uri,a.id as id,a.item_id as pId,a.title as name,c.mime as type,3 as level,a.sequence,a.resourse_id as resourceId,a.create_by,c.type AS file_type,b.mime_type FROM t_course_item_resource_reference a LEFT JOIN t_resource_info b ON a.resourse_id=b.id LEFT JOIN t_resource_file c ON b.file_id=c.id WHERE a.item_id=:itemId AND a.course_id=:courseId AND a.del_flag=0 AND b.del_flag=0 AND c.del_flag=0 ORDER BY a.sequence asc";
                                $resourceList = \Yii::$app->db->createCommand($sql)->bindValue(':itemId', $value['id'])->bindValue(':courseId', $course_id)->queryAll();
                                $resourceList_news = [];
                                foreach ($resourceList as $resource) {
                                    if(in_array($resource['file_type'],['doc','docx'])){
                                        $icon=$url."/weixin/course/01.png";
                                    }elseif(in_array($resource['file_type'],['png','jpg','jpeg','JPG','PNG','JPEG','bmp','gif'])){
                                        $icon=$url."/weixin/course/02.png";
                                    }elseif(in_array($resource['file_type'],['xls','xlsx'])){
                                        $icon=$url."/weixin/course/03.png";
                                    }elseif($resource['file_type']=='pdf'){
                                        $icon=$url."/weixin/course/04.png";
                                    }elseif($resource['file_type']=='txt'){
                                        $icon=$url."/weixin/course/05.png";
                                    }elseif(in_array($resource['file_type'],['ppt','pptx'])){
                                        $icon=$url."/weixin/course/06.png";
                                    }elseif($resource['file_type']=='swf'){
                                        $icon=$url."/weixin/course/07.png";
                                    }elseif(in_array($resource['file_type'],['html','htm'])){
                                        $icon=$url."/weixin/course/08.png";
                                    }elseif(in_array($resource['file_type'],['ogg','ogv','mov','webm','mp3','wav','mid'])){
                                        $icon=$url."/weixin/course/09.png";
                                    }else if(in_array($resource['file_type'],['flv','mkv','avi','rm','rmvb','mp4','wmv'])){
                                        $icon=$url."/weixin/course/10.png";
                                    }else{
                                        $icon=$url."/weixin/course/11.png";
                                    }
                                    $resourceList_news[] = array('id' => $resource['id'], 'pId' => $resource['pId'], 'name' => $resource['name'], 'type' => $resource['type'], 'level' => $resource['level'], 'sequence' => $resource['sequence'], 'resourceId' => empty($resource['resourceId']) ? '' : $resource['resourceId'], 'create_by' => $resource['create_by'],'uri' => $resource['uri'],'file_type'=>$resource['file_type'],'mime_type'=>$resource['mime_type'],'icon'=>$icon);
                                }
                                $siji[] = array_merge($value, array('children' => $resourceList_news));
                            } else {
                                $siji[] = $value;
                            }
                        }
                        $sanji[] = array_merge($erji, array('children' => $siji));
                    } else {
                        if(in_array($erji['file_type'],['doc','docx'])){
                            $icon=$url."/weixin/course/01.png";
                        }elseif(in_array($erji['file_type'],['png','jpg','jpeg','JPG','PNG','JPEG','bmp','gif'])){
                            $icon=$url."/weixin/course/02.png";
                        }elseif(in_array($erji['file_type'],['xls','xlsx'])){
                            $icon=$url."/weixin/course/03.png";
                        }elseif($erji['file_type']=='pdf'){
                            $icon=$url."/weixin/course/04.png";
                        }elseif($erji['file_type']=='txt'){
                            $icon=$url."/weixin/course/05.png";
                        }elseif(in_array($erji['file_type'],['ppt','pptx'])){
                            $icon=$url."/weixin/course/06.png";
                        }elseif($erji['file_type']=='swf'){
                            $icon=$url."/weixin/course/07.png";
                        }elseif(in_array($erji['file_type'],['html','htm'])){
                            $icon=$url."/weixin/course/08.png";
                        }elseif(in_array($erji['file_type'],['ogg','ogv','mov','webm','mp3','wav','mid'])){
                            $icon=$url."/weixin/course/09.png";
                        }else if(in_array($erji['file_type'],['flv','mkv','avi','rm','rmvb','mp4','wmv'])){
                            $icon=$url."/weixin/course/10.png";
                        }else{
                            $icon=$url."/weixin/course/11.png";
                        }
                        $erji['icon']=$icon;
                        $sanji[] = $erji;
                    }
                }
                $yiji[] = array('id' => $chapter['id'], 'pId' => $chapter['pid'], 'name' => $chapter['title'], 'type' => 'directory', 'level' => '1', 'create_by' => $chapter['create_by'], 'children' => $sanji);
            }
            if(!empty($yiji)){
                $result = [
                    'msg' => '操作成功',
                    'ver' => '1.5.0',
                    'data' => $yiji,
                    'code' => '200'
                ];
            }else{
                $result = [
                    'msg' => '操作失败',
                    'ver' => '1.5.0',
                    'data' => ['操作失败'],
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }

    /**
     * 微信小程序根据资源ID查询资源详情
     * @param int courseId:课程ID userId：用户ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2019-12-25
     * @author: gyq
     */
    public function actionGetResourceInfoById(){
        ini_set('memory_limit','512M');
        set_time_limit(0);
        $resourceId=!empty($_REQUEST['resourceId'])?$_REQUEST['resourceId']:$error[]=array('资源ID不能为空');
        $courseId = isset($_REQUEST['courseId'])?$_REQUEST['courseId']:'';
        $itemId = isset($_REQUEST['itemId'])?$_REQUEST['itemId']:'';
        $userId = isset($_REQUEST['userId'])?$_REQUEST['userId']:'';
        $projectId = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:'';
        if(!empty($error)){
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' =>$error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }else{
            $sql = "SELECT tri.title,tri.source,tri.mat_status,tri.school_id,trf.size,trf.format_flag,trf.uri,trf.b_uri,trf.type,trf.mime, tbup.pet_name, tri.mat_diff, tbmd.`name` major_name, tbs.school_name, tri.mime_type, tri.mat_type, tri.create_time, tri.group_id, tri.keyword, tbpg.group_name,trf.type as file_type "
                . "FROM `t_resource_info` tri "
                . "LEFT JOIN t_resource_file trf ON tri.file_id = trf.id "
                . "LEFT JOIN t_base_user_profile tbup ON tri.create_by = tbup.user_id "
                . "LEFT JOIN t_base_school tbs ON tri.school_id = tbs.id "
                . "LEFT JOIN t_base_major_directory tbmd ON tri.major_id = tbmd.uuid "
                . "LEFT JOIN t_base_project_group tbpg ON tri.group_id = tbpg.id "
                . "WHERE tri.id = :resource_id AND tri.del_flag = 0;";
            $resourceInfo = TResourceInfo::findBySql($sql, [':resource_id'=>$resourceId])->asArray()->one();
            $url=\yii::$app->params['interFaceWeiXin'];
            if(in_array($resourceInfo['file_type'],['doc','docx'])){
                $fileType="webview";
            }elseif(in_array($resourceInfo['file_type'],['png','jpg','jpeg','JPG','PNG','JPEG','bmp','gif'])){
                $fileType="image";
            }elseif(in_array($resourceInfo['file_type'],['xls','xlsx'])){
                $fileType="webview";
            }elseif($resourceInfo['file_type']=='pdf'){
                $fileType="webview";
            }elseif($resourceInfo['file_type']=='txt'){
                $fileType="webview";
            }elseif(in_array($resourceInfo['file_type'],['ppt','pptx'])){
                $fileType="webview";
            }elseif($resourceInfo['file_type']=='swf'){
                $fileType="webview";
            }elseif(in_array($resourceInfo['file_type'],['html','htm'])){
                $fileType="webview";
            }elseif(in_array($resourceInfo['file_type'],['ogg','ogv','mov','webm','mp3','wav','mid'])){
                $fileType="radio";
            }else if(in_array($resourceInfo['file_type'],['flv','mkv','avi','rm','rmvb','mp4','wmv'])){
                $fileType="video";
            }else{
                $fileType="other";
            }
            $resourceInfo['resourceType']=$fileType;
            if(empty($resourceInfo['school_id'])){
                $resourceInfo['school_name'] = '';
            }
            $knowledgeList = BCourseKnowledgePoint::find()->where(['del_flag'=>0])->orderBy(['create_time'=>SORT_DESC,'name'=>SORT_ASC])->asArray()->all();
            $knowledgeListRef = \app\models\TResourceKnowledgePointRef::find()->select('point_id')->where(['flag'=>0,'resource_id'=>$resourceId])->asArray()->column();
            $str = '';
            if(!empty($knowledgeListRef)){
                foreach ($knowledgeList as $know){
                    if(in_array($know['id'], $knowledgeListRef)){
                        $str.=$know['name'].",";
                    }
                }
                $str=rtrim($str,',');
            }
            $resourceInfo['knowledge'] = Html::encode($str);
            if(in_array($resourceInfo['mime'],['resourceType.document','resourceType.ppt'])){
                $resourceInfo['docConvert']=true;
                $fileBaseUrl = \Yii::$app->params['fileUrlWeiXin'];
                $resourceInfo['uri']=$fileBaseUrl.(empty($resourceInfo)?'':$resourceInfo['uri']);
            }else{
                $resourceInfo['docConvert']=false;
                $resourceInfo['uri']=\yii::$app->params['fileUrlWeiXin'].$resourceInfo['uri'];
            }
            $resourceInfo['mime_type']=self::GetDictionaryNameByValue($resourceInfo['mime_type']);
            $resourceInfo['mat_type']=self::GetDictionaryNameByValue($resourceInfo['mat_type']);
            $resourceInfo['mat_diff']=self::GetDictionaryNameByValue($resourceInfo['mat_diff']);
            $resourceInfo['source']=self::GetDictionaryNameByValue($resourceInfo['source']);
            $resourceInfo['mat_status']=self::GetDictionaryNameByValue($resourceInfo['mat_status']);
            //查询
            $sql = "SELECT
					CASE
					WHEN trf.uri IS NULL THEN
						''
					WHEN trf.mime='resourceType.weblink' THEN
						trf.uri
					WHEN trf.mime='resourceType.document' THEN 
						CONCAT(
							'".Yii::$app->params['docConvertUrl']. "&furl=" .Yii::$app->params['fileUrlWeiXin']."',
							trf.uri
						)
					WHEN trf.mime='resourceType.ppt' THEN 
						CONCAT(
							'".Yii::$app->params['docConvertUrl']. "&furl=" .Yii::$app->params['fileUrlWeiXin']."',
							trf.uri
						)
					ELSE
						CONCAT(
							'".Yii::$app->params['fileUrlWeiXin']."',
							trf.uri
						)
					END AS uri,
						tri.id,tri.create_time,tcir.title,0 AS progress,trf.mime AS result_type,trf.type,trf.size,trf.play_time,trf.format_flag,tri.old_id,tri.major_id,trf.type AS file_type
					FROM
						t_course_item_resource_reference tcir
					LEFT JOIN t_resource_info tri ON tri.id = tcir.resourse_id
					LEFT JOIN t_resource_file trf ON trf.id = tri.file_id
					WHERE
						tcir.course_id = :courseId 
					AND tcir.item_id = :itemId 
					AND tri.mat_status = :status 
					AND tcir.del_flag = 0
					ORDER BY tcir.sequence asc";
                    $params = [':courseId' => $courseId, ':itemId' => $itemId, ':status' => 'resourceStatus.pass'];
                    $resource = Yii::$app->db->createCommand($sql)
                        ->bindValues($params)
                        ->queryAll();
                    if($resource)
                    {
                        $resource = \app\common\ArrayHelper::array_is_null($resource);
                        foreach ($resource as $key => $value)
                        {
                            $res = $this->getCurrent($courseId,$itemId,$value['id'],$userId,$value['result_type'],$value['play_time']);
                            $resource[$key]['progress'] = $res;
                            //查询所属专业
                            $sql="select name from t_base_major_directory where uuid=:uuid and del_flag=0";
                            $major_name=\yii::$app->db->createCommand($sql)->bindValues([':uuid'=>$value['major_id']])->queryScalar();
                            $resource[$key]['major_name']=!empty($major_name)?$major_name:'';
                            if(in_array($value['type'],['doc','docx'])){
                                $icon=$url."/weixin/resources/01.png";
                            }elseif(in_array($value['type'],['png','jpg','jpeg','JPG','PNG','JPEG','bmp','gif'])){
                                $icon=$url."/weixin/resources/02.png";
                            }elseif(in_array($value['type'],['xls','xlsx'])){
                                $icon=$url."/weixin/resources/03.png";
                            }elseif($value['type']=='pdf'){
                                $icon=$url."/weixin/resources/04.png";
                            }elseif($value['type']=='txt'){
                                $icon=$url."/weixin/resources/05.png";
                            }elseif(in_array($value['type'],['ppt','pptx'])){
                                $icon=$url."/weixin/resources/06.png";
                            }elseif($value['type']=='swf'){
                                $icon=$url."/weixin/resources/07.png";
                            }elseif(in_array($value['type'],['html','htm'])){
                                $icon=$url."/weixin/resources/08.png";
                            }elseif(in_array($value['type'],['ogg','ogv','mov','webm','mp3','wav','mid'])){
                                $icon=$url."/weixin/resources/09.png";
                            }else if(in_array($value['type'],['flv','mkv','avi','rm','rmvb','mp4','wmv'])){
                                $icon=$url."/weixin/resources/10.png";
                            }else{
                                $icon=$url."/weixin/resources/11.png";
                            }
                            //判断是否正在播放
                            if($value['id']==$resourceId){
                                $icon=$url."/weixin/resources/12.png";
                            }
                            $resource[$key]['icon']=$icon;
                        }
                    }
                    $resourceInfo['peerResources']=$resource;
                    //查询资源评价
                    $num = TCourseEvaluate::find()
                        ->select('tce.id')
                        ->alias('tce')
                        ->leftjoin('t_base_user_profile tbup','tbup.user_id=tce.create_by')
                        ->where('tce.object_id=:resourceId and tce.course_id=:courseId and tce.type=:type and tce.del_flag=0', [':resourceId' => $resourceId, ':courseId' => $courseId, 'type' => 'praiseStudentOrTeacher.studenToResource'])
                        ->all();
                    $resourceInfo['totalNum']=count($num);
                    $result = [
                        'msg' => '查询成功',
                        'ver' => '1.5.0',
                        'data' => $resourceInfo,
                        'code' => '200'
                    ];
                    Yii::$app->end(json_encode($result));
        }
    }
    public function actionAppGetItemResourceList()
    {
        $error = array();
        $courseId = isset($_REQUEST['courseId'])?$_REQUEST['courseId']:$error[]=array('课程ID不能为空');
        $itemId = isset($_REQUEST['itemId'])?$_REQUEST['itemId']:$error[]=array('章节ID不能为空');
        $userId = isset($_REQUEST['userId'])?$_REQUEST['userId']:$error[]=array('用户ID不能为空');
        $projectId = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        if(!empty($error))
        {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }
        else
        {
            $sql = "SELECT
					CASE
					WHEN trf.uri IS NULL THEN
						''
					WHEN trf.mime='resourceType.weblink' THEN
						trf.uri
					WHEN trf.mime='resourceType.document' THEN 
						CONCAT(
							'".Yii::$app->params['docConvertUrl']. "&furl=" .Yii::$app->params['fileUrlWeiXin']."',
							trf.uri
						)
					WHEN trf.mime='resourceType.ppt' THEN 
						CONCAT(
							'".Yii::$app->params['docConvertUrl']. "&furl=" .Yii::$app->params['fileUrlWeiXin']."',
							trf.uri
						)
					ELSE
						CONCAT(
							'".Yii::$app->params['fileUrlWeiXin']."',
							trf.uri
						)
					END AS uri,
						tri.id,tri.create_time,tcir.title,0 AS progress,trf.mime AS result_type,trf.type,trf.size,trf.play_time,trf.format_flag,tri.old_id
					FROM
						t_course_item_resource_reference tcir
					LEFT JOIN t_resource_info tri ON tri.id = tcir.resourse_id
					LEFT JOIN t_resource_file trf ON trf.id = tri.file_id
					WHERE
						tcir.course_id = :courseId 
					AND tcir.item_id = :itemId 
					AND tri.mat_status = :status 
					AND tcir.del_flag = 0
					ORDER BY tcir.sequence asc";
            $params = [':courseId' => $courseId, ':itemId' => $itemId, ':status' => 'resourceStatus.pass'];
            $resource = Yii::$app->db->createCommand($sql)
                ->bindValues($params)
                ->queryAll();
            if($resource)
            {
                $resource = \app\common\ArrayHelper::array_is_null($resource);
                foreach ($resource as $key => $value)
                {
                    $res = $this->getCurrent($courseId,$itemId,$value['id'],$userId,$value['result_type'],$value['play_time']);
                    $resource[$key]['progress'] = $res;
                }
                $result = [
                    'msg' => '查找成功',
                    'ver' => '1.5.0',
                    'data' => $resource,
                    'success' => true,
                    'code' => '200'
                ];
            }
            elseif(empty($resource))
            {
                $result = [
                    'msg' => '没有查询到相关数据',
                    'ver' => '1.5.0',
                    'data' => ['没有查询到相关数据'],
                    'success' => false,
                    'code' => '404'
                ];
            }
            elseif($resource===false)
            {
                $result = [
                    'msg' => '查找失败',
                    'ver' => '1.5.0',
                    'data' => ['查找失败'],
                    'success' => false,
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * 微信小程序资源评价列表接口
     * @param int  courseId:课程ID resourceId:资源ID  projectId:联盟ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2019-12-27
     * @author: gyq
     */
    public function actionAppGetResourceEvaluateList()
    {
        $error = array();
        $resourceId = isset($_REQUEST['resourceId'])?$_REQUEST['resourceId']:$error[]=array('资源ID不能为空');
        $courseId = isset($_REQUEST['courseId'])?$_REQUEST['courseId']:$error[]=array('课程ID不能为空');
//        $userId = isset($_REQUEST['userId'])?$_REQUEST['userId']:$error[]=array('用户ID不能为空');
//        $projectId = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        $pageSize = isset($_REQUEST['pageSize'])?$_REQUEST['pageSize']:'20';
        $page = isset($_REQUEST['page'])?$_REQUEST['page']:'1';
        $offset = ($page-1)*$pageSize;
        if(!empty($error))
        {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }
        else
        {
            $num = TCourseEvaluate::find()
                ->select('tce.id')
                ->alias('tce')
                ->leftjoin('t_base_user_profile tbup','tbup.user_id=tce.create_by')
                ->where('tce.object_id=:resourceId and tce.course_id=:courseId and tce.type=:type and tce.del_flag=0', [':resourceId' => $resourceId, ':courseId' => $courseId, 'type' => 'praiseStudentOrTeacher.studenToResource'])
                ->all();
            $evaluate = TCourseEvaluate::find()
                ->select('tce.id,tce.content,tce.create_time,tbup.url_image,tbup.pet_name,tce.praise,tce.create_by,tce.old_id')
                ->alias('tce')
                ->leftjoin('t_base_user_profile tbup','tbup.user_id=tce.create_by')
                ->where('tce.object_id=:resourceId and tce.course_id=:courseId and tce.type=:type and tce.del_flag=0', [':resourceId' => $resourceId, ':courseId' => $courseId, 'type' => 'praiseStudentOrTeacher.studenToResource'])
                ->asArray()
                ->offset($offset)
                ->limit($pageSize)
                ->orderBy('create_time desc')
                ->all();
            if($evaluate)
            {
                $evaluate = self::array_is_null($evaluate);
                foreach ($evaluate as $key =>& $val)
                {
                    $val['praise'] = intval($val['praise']);
                    $sql = "SELECT id FROM t_course_evaluate_user_relation WHERE object_id='".$val['id']."' AND course_id='".$courseId."'  AND del_flag=0";
                    $praise = \Yii::$app->db->createCommand($sql)->queryOne();
                    if($praise)
                    {
                        $val['status'] = "yesOrNo.yes";
                    }
                    else
                    {
                        $val['status'] = "yesOrNo.no";
                    }
                    if(!empty($val['url_image']))
                    {
                        $val['url_image'] = Yii::$app->params['fileUrlWeiXin'].$val['url_image'];
                    }
                    if(empty($val['pet_name']))
                    {
                        $name_sql = "SELECT username FROM t_base_user WHERE id='".$val['create_by']."' AND del_flag=0";
                        $name = \Yii::$app->db->createCommand($name_sql)->queryOne();
                        $val['pet_name'] = $name['username'];
                    }
                    unset($val['create_by']);
                }
                $result = [
                    'msg' => '查找成功',
                    'ver' => '1.5.0',
                    'num' => count($num),
                    'data' => $evaluate,
                    'success' => true,
                    'code' => '200'
                ];
            }
            elseif(empty($evaluate))
            {
                $result = [
                    'msg' => '没有查询到相关数据',
                    'ver' => '1.5.0',
                    'data' => [],
                    'num' => count($num),
                    'success' => false,
                    'code' => '200'
                ];
            }
            elseif($evaluate===false)
            {
                $result = [
                    'msg' => '查找失败',
                    'ver' => '1.5.0',
                    'data' => ['查找失败'],
                    'num' => count($num),
                    'success' => false,
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * 微信小程序保存资源评价接口
     * @param int  courseId:课程ID userId:用户ID objectId:资源ID  projectId:联盟ID
     * @param string  content:评价内容
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2019-12-27
     * @author: gyq
     */
    public function actionAppSaveResourceEvaluate()
    {
        $error = array();
        $userId = !empty($_REQUEST['userId'])?$_REQUEST['userId']:$error[]=array('用户ID不能为空');
        $objectId = !empty($_REQUEST['objectId'])?$_REQUEST['objectId']:$error[]=array('资源ID不能为空');
        $content = !empty($_REQUEST['content'])?$_REQUEST['content']:$error[]=array('评价内容不能为空');
        $courseId = !empty($_REQUEST['courseId'])?$_REQUEST['courseId']:$error[]=array('课程ID不能为空');
        $projectId = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        if(!empty($error))
        {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }
        else
        {
            $evaluate = new TCourseEvaluate();
            $uuid = Uuid::uuid();
            $evaluate->attributes = $_REQUEST;
            $evaluate->id = $uuid;
            $evaluate->type = 'praiseStudentOrTeacher.studenToResource';
            $evaluate->content = $content;
            $evaluate->praise = 0;
            $evaluate->course_id = $courseId;
            $evaluate->object_id = $objectId;
            $evaluate->create_by = $userId;
            $evaluate->create_time = date("Y-m-d H:i:s",time());
            $evaluate->del_flag = 0;
            $evaluate->old_id = $uuid;
            if($evaluate->validate() && $evaluate->save())
            {
                $result = [
                    'msg' => '保存成功',
                    'ver' => '1.5.0',
                    'data' => ['old_id'=>$evaluate->old_id],
                    'success' => true,
                    'code' => '200'
                ];
            }
            else
            {
                $result = [
                    'msg' => '保存失败',
                    'ver' => '1.5.0',
                    'data' => ['保存失败'],
                    'success' => false,
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * mysql 查询出的数组 null 转 ''
     * @param type $arr
     * @return type
     */
    public static function array_is_null($arr){
        $new_array = array();
        if(count($arr) == count($arr,1)){
            foreach ($arr as $key =>$a){
                $new_array[$key] = $a==NULL?'':$a;
            }
            return $new_array;
        }else{
            foreach ($arr as $key =>$a){
                foreach ($a as $k => $val) {
                    $new_array[$key][$k] = $val==NULL?'':$val;
                }
            }
            return $new_array;
        }
    }
    public static function GetDictionaryNameByValue($value){
        $sql="select name from t_sys_dictionary where del_flag=0 and value=:value";
        $result=\yii::$app->db->createCommand($sql)->bindValues([':value'=>$value])->queryScalar();
        if(!empty($result)){
            return $result;
        }
        return "";
    }
    public function getCurrent($course_id, $item_id, $resource_id, $uid, $mime_type, $play_time) {
        $sql = "select current_progress,is_end from t_course_items_video_current where course_id=:cid and item_id=:item_id and resource_id=:rid and user_id=:uid and del_flag=0";
        $current = \Yii::$app->db->createCommand($sql)->bindValue(':cid', $course_id)->bindValue(':item_id', $item_id)->bindValue(':rid', $resource_id)->bindValue(':uid', $uid)->queryOne();
        if ($mime_type == 'resourceType.video') {
            if (!empty($current)) {
                if ($current['is_end'] == 'yesOrNo.yes') {
                    return 100;
                } else {
                    if(!empty($play_time)){
                        $arr = explode(':', $play_time);
                        $len = count($arr);
                        if($len != 3){
                            $play_time = 0;
                        }else{
                            $time = (int)$arr[$len - 1] + (int)$arr[$len - 2] * 60 + (($len > 2 ? (int)$arr[$len - 3] : 0) * 60 * 60);
                        }
                    }else{
                        $play_time = 0;
                    }
                    return $play_time == "" ? 100 : ceil($current['current_progress']/$time*100);
                }
            } else {
                return 0;
            }
        } else {
            if ($current['is_end'] == 'yesOrNo.yes') {
                return 100;
            } else {
                return 0;
            }
        }
    }
    /**
     * 微信小程序视频进度接口
     * @param int  note_id:笔记ID userId:用户ID  projectId:联盟ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 20120-01-06
     * @author: gyq
     */
    public function actionAppSaveMyVideoRate()
    {
        $error = array();
        $courseId = !empty($_REQUEST['courseId'])?$_REQUEST['courseId']:$error[]=array('课程ID不能为空');
        $itemId = !empty($_REQUEST['itemId'])?$_REQUEST['itemId']:$error[]=array('章节ID不能为空');
        $fileId = !empty($_REQUEST['fileId'])?$_REQUEST['fileId']:$error[]=array('视频ID不能为空');
        $userId = !empty($_REQUEST['userId'])?$_REQUEST['userId']:$error[]=array('用户ID不能为空');
        $type = !empty($_REQUEST['type'])?$_REQUEST['type']:$error[]=array('类型不能为空');
        $current_progress = !empty($_REQUEST['current_progress'])?$_REQUEST['current_progress']:$error[]=array('进度不能为空');
        $is_end = !empty($_REQUEST['is_end'])?$_REQUEST['is_end']:'';
        $projectId = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        if(!empty($error)){
            $result = array(
                "msg"=> "参数缺失",
                "ver"=> "1.5.0",
                'data'=>$error,
                'code'=>'601'
            );
            Yii::$app->end(json_encode($result));
        }
        else
        {
            $data = \app\models\TCourseItemsVideoCurrent::find()
                ->where('course_id=:courseId and item_id=:itemId and resource_id=:fileId and user_id=:userId and del_flag=0', [
                    ':courseId' => $courseId,
                    ':itemId' => $itemId,
                    ':fileId' => $fileId,
                    ':userId' => $userId
                ])
                ->one();
            if(!empty($data))
            {
                if($data->current_progress>$current_progress){
                    $result = [
                        'msg' => '操作成功',
                        'ver' => '1.5.0',
                        'data' => ['操作成功'],
                        'success' => true,
                        'code' => '200'
                    ];
                    Yii::$app->end(json_encode($result));
                }
                $data->current_progress = $current_progress;
                if(!empty($is_end))
                {
                    $data->is_end = $is_end;
                }
                $data->update_by = $userId;
                $data->update_time = date("Y-m-d H:i:s");
                if($data->save())
                {
                    $result = [
                        'msg' => '操作成功',
                        'ver' => '1.5.0',
                        'data' => ['操作成功'],
                        'success' => true,
                        'code' => '200'
                    ];
                }
                else
                {
                    $result = [
                        'msg' => '操作失败',
                        'ver' => '1.5.0',
                        'data' => ['操作失败'],
                        'success' => false,
                        'code' => '400'
                    ];
                }
            }
            else
            {
                $model = new \app\models\TCourseItemsVideoCurrent();
                $model->attributes = $_REQUEST;
                $model->id = Uuid::uuid();
                $model->course_id = $courseId;
                $model->item_id = $itemId;
                $model->resource_id = $fileId;
                $model->type = $type;
                $model->user_id = $userId;
                $model->current_progress = $current_progress;
                $model->is_end = $is_end;
                $model->create_by = $userId;
                $model->create_time = date("Y-m-d H:i:s");
                $model->del_flag = 0;
                if($model->validate() && $model->save())
                {
                    $result = [
                        'msg' => '操作成功',
                        'ver' => '1.5.0',
                        'data' => ['操作成功'],
                        'success' => true,
                        'code' => '200'
                    ];
                }
                else
                {
                    $result = [
                        'msg' => '操作失败',
                        'ver' => '1.5.0',
                        'data' => ['操作失败'],
                        'success' => false,
                        'code' => '400'
                    ];
                }
            }
            Yii::$app->end(json_encode($result));
        }
    }
}
?>